package in.ac.dei.edrp.cms.daoimpl.registration.mastertransferdaoimpl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.aspectj.util.LangUtil.ProcessController;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.sun.org.apache.commons.digester.SetRootRule;

import in.ac.dei.edrp.cms.constants.CRConstant;
import in.ac.dei.edrp.cms.domain.activitymaster.CountProcessRecorList;
import in.ac.dei.edrp.cms.domain.registration.prestaging.AddressDetailBean;
import in.ac.dei.edrp.cms.domain.registration.prestaging.CourseList;

import in.ac.dei.edrp.cms.domain.registration.prestaging.MasterTransferBean;
import in.ac.dei.edrp.cms.domain.registration.prestaging.OldSemesterDetails;
import in.ac.dei.edrp.cms.domain.registration.prestaging.PersonalDetailsBean;

import in.ac.dei.edrp.cms.domain.registration.prestaging.TransferNORInPSTBean;
import in.ac.dei.edrp.cms.domain.utility.EmailTableBean;
import in.ac.dei.edrp.cms.domain.utility.ErrorLogs;
import in.ac.dei.edrp.cms.domain.utility.ErrorReason;
import in.ac.dei.edrp.cms.domain.utility.StudentTracking;
import in.ac.dei.edrp.cms.domain.utility.SystemValue;
import in.ac.dei.edrp.cms.utility.CRException;
import in.ac.dei.edrp.cms.utility.PreviousSemesterDetail;
import in.ac.dei.edrp.cms.utility.RegistrationFunction;
import in.ac.dei.edrp.cms.utility.StudentTrackingFunction;

public class TransferTempIntoMaster{

	private TransactionTemplate transactionTemplate=null;
	
	private SqlMapClient sqlMapClient=null;
		
	public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
		this.transactionTemplate = transactionTemplate;
	}

	public void setSqlMapClient(SqlMapClient sqlMapClient) {
		this.sqlMapClient = sqlMapClient;
	}

	public TransferTempIntoMaster(SqlMapClient sqlMapClient,TransactionTemplate transactionTemplate){
		this.sqlMapClient=sqlMapClient;
		this.transactionTemplate=transactionTemplate;
	}
	
	public TransferTempIntoMaster(){
		
	}

	public CountProcessRecorList transferTempToMaster(MasterTransferBean masterTransferBeanObject){
	
		CountProcessRecorList countList=new CountProcessRecorList();
	RegistrationFunction registrationFunction=new RegistrationFunction(sqlMapClient,transactionTemplate);
	ErrorLogs errorLogs=new ErrorLogs(masterTransferBeanObject.getNewEntity(),masterTransferBeanObject.getNewProgram(),masterTransferBeanObject.getNewBranch(),masterTransferBeanObject.getNewSpecialization(),
			masterTransferBeanObject.getNewSemester(),masterTransferBeanObject.getSemesterStartDate(),masterTransferBeanObject.getSemesterEndDate(),
			masterTransferBeanObject.getProcessId(),masterTransferBeanObject.getActivityId());
	
	List<MasterTransferBean> normalList=new ArrayList<MasterTransferBean>();
	List<MasterTransferBean> switchList=new ArrayList<MasterTransferBean>();
	List<MasterTransferBean> newList=new ArrayList<MasterTransferBean>();
	
	boolean processedFlag=false;
	
	int recordsFailed=0;
	int rejectedValue=0;
	int processedStudent=0;
		try{
			
			 String universityId=masterTransferBeanObject.getUniveristyId();
			 String userId=masterTransferBeanObject.getUserId();
			 
			 String entityId=masterTransferBeanObject.getNewEntity();
			 String programId=masterTransferBeanObject.getNewProgram();
			 String branchId=masterTransferBeanObject.getNewBranch();
			 String specializationId=masterTransferBeanObject.getNewSpecialization();
			 String semesterCode=masterTransferBeanObject.getNewSemester();
			 String semesterStartDate=masterTransferBeanObject.getSemesterStartDate();
			 String semesterEndDate=masterTransferBeanObject.getSemesterEndDate();
			 String programCourseKey=masterTransferBeanObject.getProgramCourseKey();
			 
			 String sessionStartDate=masterTransferBeanObject.getSessionStartDate();
			 String sessionEndDate=masterTransferBeanObject.getSessionEndDate();
			 
			 String processId=masterTransferBeanObject.getProcessId();
			 String activityId=masterTransferBeanObject.getActivityId();
			 
			 int processCount=masterTransferBeanObject.getProcessCount();
			 errorLogs.setProcessCounter(processCount);
			 
			 System.out.println(entityId+programId+branchId+specializationId+semesterCode+
					 semesterStartDate+semesterEndDate+masterTransferBeanObject.getSessionStartDate()+masterTransferBeanObject.getSessionEndDate()+
					 universityId+userId);
		 
			 masterTransferBeanObject.setAdmissionMode(CRConstant.NORMAL_MODE);
			 masterTransferBeanObject.setRegistrationStatus("G");
			 
			 MasterTransferBean masterNorrmalBeanObject=masterTransferBeanObject;
			//get list of student having admission mode NOR in temp_student_program
		normalList=(List<MasterTransferBean>)sqlMapClient.queryForList("masterTransfer.getListOfStudentWithAdmissionMode", masterNorrmalBeanObject);
		System.out.println("Normal records:"+normalList.size());
				
		for(MasterTransferBean masterTransferBean:normalList){
			
			//List of courses of student from temp_student_courses
			masterTransferBean.setNewProgram(programId);
			masterTransferBean.setNewBranch(branchId);
			masterTransferBean.setNewSpecialization(specializationId);
			masterTransferBean.setNewSemester(semesterCode);
			masterTransferBean.setSemesterStartDate(semesterStartDate);
			masterTransferBean.setSemesterEndDate(semesterEndDate);
			masterTransferBean.setProgramCourseKey(programCourseKey);
			masterTransferBean.setUserId(userId);
			
			List<CourseList> courseList=getCourseListForOldStudent(masterTransferBean);
			ErrorReason errorReason=new ErrorReason();
			
			//List of courses:
			//System.out.println("List of courses: "+courseList+"program Course key"+programCourseKey);
			try{
				errorLogs.setEnrollmentNumber(masterTransferBean.getEnrollmentNumber());
				errorLogs.setStudentId(masterTransferBean.getStudentId());
				errorLogs.setStudentName(getStudentName(errorLogs));
				
			masterNorrmalBeanObject=new MasterTransferBean(
					universityId,entityId,programId,branchId,specializationId,semesterCode,
					semesterStartDate,semesterEndDate,masterTransferBean.getOldEntity(),
					masterTransferBean.getOldProgram(),masterTransferBean.getOldBranch(),
					masterTransferBean.getOldSpecialization(),masterTransferBean.getOldSemester(),
					masterTransferBean.getEnrollmentNumber(),masterTransferBean.getRollNumber(),
					masterTransferBean.getOldRollNumber(),masterTransferBean.getStudentId(),CRConstant.NORMAL_MODE,
					masterTransferBean.getStatusInSemester(),masterTransferBean.getRegisterDate(),
					masterTransferBean.getRegistrationStatus(),masterTransferBean.getSequenceNumber(),
					courseList,programCourseKey,userId,sessionStartDate,sessionEndDate,activityId,processCount);
			

			errorReason=validateDataForNORStudent(masterNorrmalBeanObject,courseList);
			
			if(errorReason.isValidRecord()){
								
				transferNORStudentIntoMaster(masterNorrmalBeanObject,errorLogs);
				processedStudent++;

			}
			else{
				
				System.out.println("Student Name: "+getStudentName(errorLogs));
				
				errorLogs.setReasonCode("DBI");
				errorLogs.setDescription("Unknown issue");
			
				errorLogs.setProcessFlag(CRConstant.ERROR_STATUS);
				
				rejectedValue++;
				
				sqlMapClient.insert("studentTrackingAndLogs.insertStudentErrorLog", errorLogs);
			}
			}catch(Exception normalException){
				System.out.println("Student Name: "+getStudentName(errorLogs));
				
				errorLogs.setReasonCode("DBI");
				errorLogs.setDescription("Unknown issue");
			
				errorLogs.setProcessFlag(CRConstant.ERROR_STATUS);
				
				recordsFailed++;
				sqlMapClient.insert("studentTrackingAndLogs.insertStudentErrorLog", errorLogs);
				System.out.println("Exception inside student error logs:"+normalException.getMessage());
			}
		}
			//get list of student having admission mode SWT in temp_student_program
		MasterTransferBean masterSwitchBeanObject=masterTransferBeanObject;
		masterSwitchBeanObject.setAdmissionMode(CRConstant.SWITCH_MODE);
		switchList=(List<MasterTransferBean>)sqlMapClient.queryForList("masterTransfer.getListOfStudentWithAdmissionMode", masterSwitchBeanObject);
		
		System.out.println("Switch student"+switchList.size());
		for(MasterTransferBean masterTransferBean:switchList){
			
			//List of courses of student from temp_student_courses
			masterTransferBean.setNewProgram(programId);
			masterTransferBean.setNewBranch(branchId);
			masterTransferBean.setNewSpecialization(specializationId);
			masterTransferBean.setNewSemester(semesterCode);
			masterTransferBean.setSemesterStartDate(semesterStartDate);
			masterTransferBean.setSemesterEndDate(semesterEndDate);
			masterTransferBean.setProgramCourseKey(programCourseKey);
			masterTransferBean.setUserId(userId);
			
			List<CourseList> courseList=(List<CourseList>)getCourseListForOldStudent(masterTransferBean);
			
			OldSemesterDetails oldSemesterDetail=getOldProgramDetails(masterTransferBean);
			
			ErrorReason errorReason=new ErrorReason();
			try{
				errorLogs.setEnrollmentNumber(masterTransferBean.getEnrollmentNumber());
				errorLogs.setStudentId(masterTransferBean.getStudentId());
				errorLogs.setStudentName(getStudentName(errorLogs));
				masterSwitchBeanObject=new MasterTransferBean(
						universityId,entityId,programId,branchId,specializationId,semesterCode,
						semesterStartDate,semesterEndDate,masterTransferBean.getOldEntity(),
						masterTransferBean.getOldProgram(),masterTransferBean.getOldBranch(),
						masterTransferBean.getOldSpecialization(),masterTransferBean.getOldSemester(),
						masterTransferBean.getEnrollmentNumber(),masterTransferBean.getRollNumber(),
						oldSemesterDetail.getOldRollNumber(),masterTransferBean.getStudentId(),CRConstant.SWITCH_MODE,
						masterTransferBean.getStatusInSemester(),masterTransferBean.getRegisterDate(),
						masterTransferBean.getRegistrationStatus(),masterTransferBean.getSequenceNumber(),
						courseList,programCourseKey,userId,sessionStartDate,sessionEndDate,activityId,processCount);
		
			errorReason=validateDataForSWTStudent(masterSwitchBeanObject,courseList,oldSemesterDetail);
			if(errorReason.isValidRecord()){
				
				transferSWTStudentIntoMaster(masterSwitchBeanObject,oldSemesterDetail,errorLogs);
				processedStudent++;
	
			}
			else{
				
				errorLogs.setReasonCode(errorReason.getReasonCode());
				errorLogs.setDescription(errorReason.getDescription());
				errorLogs.setProcessFlag(CRConstant.ERROR_STATUS);
				rejectedValue++;
				sqlMapClient.insert("studentTrackingAndLogs.insertStudentErrorLog", errorLogs);
			}
			}catch(Exception switchException){
				System.out.println("Coming inside exception switch "+switchException.getMessage());
				
				errorLogs.setReasonCode("DBI");
				errorLogs.setDescription("Database inconsistancy");
				errorLogs.setProcessFlag(CRConstant.ERROR_STATUS);
				
				recordsFailed++;
				sqlMapClient.insert("studentTrackingAndLogs.insertStudentErrorLog", errorLogs);
			}
		}	
	
			
		//get list of student having admission mode NEW in temp_student_program
		MasterTransferBean masterNewBeanObject=masterTransferBeanObject;
		masterNewBeanObject.setAdmissionMode(CRConstant.NEW_MODE);
		newList=(List<MasterTransferBean>)sqlMapClient.queryForList("masterTransfer.getListOfStudentWithAdmissionMode", masterTransferBeanObject);
		
		System.out.println("Total new stduent:"+newList.size());
		
		for(MasterTransferBean masterTransferBean:newList){
			PersonalDetailsBean personalDetailsBean=new PersonalDetailsBean(universityId,
					masterTransferBean.getEnrollmentNumber(),userId);
			
			
			//object with personal details of a student
			PersonalDetailsBean personalDetails=getPersonDetails(personalDetailsBean);
			
			//List of courses of student from temp_student_courses
			masterTransferBean.setNewProgram(programId);
			masterTransferBean.setNewBranch(branchId);
			masterTransferBean.setNewSpecialization(specializationId);
			masterTransferBean.setNewSemester(semesterCode);
			masterTransferBean.setSemesterStartDate(semesterStartDate);
			masterTransferBean.setSemesterEndDate(semesterEndDate);
			masterTransferBean.setProgramCourseKey(programCourseKey);
			masterTransferBean.setUserId(userId);
			
			List<CourseList> courseList=getCourseList(masterTransferBean);
			ErrorReason errorReason=new ErrorReason();
			try{
			masterNewBeanObject=new MasterTransferBean(
					universityId,entityId,programId,branchId,specializationId,semesterCode,
					semesterStartDate,semesterEndDate,
					
					masterTransferBean.getOldEntity(),masterTransferBean.getOldProgram(),masterTransferBean.getOldBranch(),
					masterTransferBean.getOldSpecialization(),masterTransferBean.getOldSemester(),
					
					masterTransferBean.getEnrollmentNumber(),masterTransferBean.getRollNumber(),
					
					masterTransferBean.getOldRollNumber(),masterTransferBean.getStudentId(),
					
					CRConstant.NEW_MODE,masterTransferBean.getStatusInSemester(),
					CRConstant.REGULAR_ADMISSION_MODE,masterTransferBean.getRegistrationStatus(),
					masterTransferBean.getSequenceNumber(),courseList,programCourseKey,userId,sessionStartDate,sessionEndDate,activityId,processCount);
			//To set mode of entry with RG: Regular
			//masterTransferBeanObject.setModeOfEntry(CRConstant.REGULAR_ADMISSION_MODE);
			
			personalDetails.setUniversityId(universityId);
			personalDetails.setEnrollmentNumber(masterTransferBean.getEnrollmentNumber());
			personalDetails.setUserId(userId);
			personalDetails.setEntityId(entityId);
			personalDetails.setRegisteredInSession(sessionStartDate.substring(0,4)+"-"+sessionEndDate.substring(2,4));
			
			errorReason=validateDataForNEWStudent(masterNewBeanObject,courseList,personalDetails);
			
			errorLogs.setEnrollmentNumber(masterTransferBean.getEnrollmentNumber());
			errorLogs.setStudentId(masterTransferBean.getStudentId());
			errorLogs.setStudentName(getStudentName(errorLogs));
			
			if(errorReason.isValidRecord()){
				
				transferNEWStudentIntoMaster(masterNewBeanObject,personalDetails,errorLogs);
				processedStudent++;
		
			}
			else{
				errorLogs.setReasonCode(errorReason.getReasonCode());
				errorLogs.setDescription(errorReason.getDescription());
				errorLogs.setProcessFlag(CRConstant.ERROR_STATUS);
				rejectedValue++;
				sqlMapClient.insert("studentTrackingAndLogs.insertStudentErrorLog", errorLogs);
			}
			}catch(Exception newException){
				
				errorLogs.setReasonCode("DBI");
				errorLogs.setDescription("Database inconsistancy");
				errorLogs.setProcessFlag(CRConstant.ERROR_STATUS);
				recordsFailed++;
				sqlMapClient.insert("studentTrackingAndLogs.insertStudentErrorLog", errorLogs);
			}
		}
			
		}catch(Exception e){
		System.out.println("Exception is transfer temporary to CR master database:"+e);
		//recordsFailed++;
	}
	finally{
		
		int actualRecords=normalList.size()+switchList.size()+newList.size();
//		String processFlag=CRConstant.INACTIVE_STATUS;
		
		System.out.println(actualRecords+"="+processedStudent);
		if(actualRecords==processedStudent && actualRecords!=0){
			System.out.println("Coming here");
//			processFlag=CRConstant.COMPLETE_STATUS;
			processedFlag=true;
		}

		
		countList=new CountProcessRecorList(actualRecords,processedStudent,rejectedValue,recordsFailed,processedFlag);
	}
	
		return countList;
	
	}
	
	

	
	
	public String getStudentName(ErrorLogs errorLog) {
		// TODO Auto-generated method stub
		String studentName="";
		try{
		List<ErrorLogs> nameList=sqlMapClient.queryForList("studentTrackingAndLogs.getStudentNameForErrorLog",errorLog);
		System.out.println(errorLog.getEnrollmentNumber()+errorLog.getStudentId());
		for(ErrorLogs error:nameList){
			System.out.println("Student Name: "+error.getStudentName());
			studentName=error.getStudentName();
		}
		
		}catch(Exception e){
			System.out.println("Exception in getting name"+e.getMessage());
		}
		return studentName;
	}

	public void transferNORStudentIntoMaster(final MasterTransferBean masterTransferBean,final ErrorLogs errorLogs){
		
		transactionTemplate.execute(new TransactionCallbackWithoutResult(){
			Object save=null;
		
			@Override
			public void doInTransactionWithoutResult(TransactionStatus status) {
			try{
				save=status.createSavepoint();
				System.out.println("coming here in Nor student transaction");
				List<CourseList> list=masterTransferBean.getCourseList();
				
				for(CourseList courseList:list){
					//insert student in student courses
					System.out.println("inserting first course");
					sqlMapClient.insert("masterTransfer.insertIntoStudentCourse", courseList);
					
				}
					
			//Semester will be updated in Student Program by previous semester
			int updateSP=sqlMapClient.update("masterTransfer.updateStudentProgram", masterTransferBean);
					
			//Updates SRSH.status by REG for User Input
			int updatedSRSH=sqlMapClient.update("masterTransfer.updateSRSHByREG", masterTransferBean);
			
			//update registration status by M
			int updateTSP=sqlMapClient.update("masterTransfer.updateTempStudentProgram", masterTransferBean);
			
			int updateTSC=sqlMapClient.update("masterTransfer.updateTempStudentCourse", masterTransferBean);
		
			StudentTracking studentTracking=new StudentTracking(masterTransferBean.getNewEntity(),masterTransferBean.getRollNumber(),
					masterTransferBean.getProgramCourseKey(),masterTransferBean.getSemesterStartDate(),masterTransferBean.getSemesterEndDate(),
					masterTransferBean.getSessionStartDate(),masterTransferBean.getSessionEndDate(),CRConstant.REGISTRATION_STATUS,
					CRConstant.ACTIVE_STATUS,masterTransferBean.getUserId(),masterTransferBean.getActivityId(),masterTransferBean.getActivityId());
			
			int sequence=new StudentTrackingFunction(sqlMapClient,transactionTemplate).getStdentTrackingIssue(studentTracking);
			
			studentTracking.setSequenceNumber(sequence+1);
			//Insert a student in student tracking with semester status YTR and program status ACT
			sqlMapClient.update("studentTrackingAndLogs.insertStudentTracking", studentTracking);
			System.out.println("Transaction is complete");
			}catch(DataAccessException e){
				System.out.println("Exception in TransferTempIntoMaster DataAccess "+e);
				errorLogs.setReasonCode("DBI");
				errorLogs.setDescription("Database inconsistancy");
				errorLogs.setProcessFlag(CRConstant.ERROR_STATUS);
				try{
				sqlMapClient.insert("studentTrackingAndLogs.insertStudentErrorLog", errorLogs);
				}catch(Exception error){
					System.out.println(error.getMessage());
				}
				// Set transaction status to rollback
//				status.rollbackToSavepoint(save);
//				status.setRollbackOnly();
//				throw new CRException("invalid update to student inside NOR");
					} catch (Exception e) {
				// TODO Auto-generated catch block
						System.out.println("Exception in TransferTempIntoMaster For Nor"+e);
						errorLogs.setReasonCode("DBI");
						errorLogs.setDescription("Database inconsistancy");
						errorLogs.setProcessFlag(CRConstant.ERROR_STATUS);
						try{
						sqlMapClient.insert("studentTrackingAndLogs.insertStudentErrorLog", errorLogs);
						}catch(Exception error){
							System.out.println(error.getMessage());
						}
					 }
			}//

			
	
        });
	}
	

	public void transferSWTStudentIntoMaster(final MasterTransferBean masterTransferBean,
			final OldSemesterDetails oldSemesterDetails,final ErrorLogs errorLogs){
		
		transactionTemplate.execute(new TransactionCallbackWithoutResult(){
			//Object savepoint=null;
		
			@Override
			public void doInTransactionWithoutResult(TransactionStatus status) {
			try{
	//			save=status.createSavepoint();
				System.out.println("Entity id "+masterTransferBean.getNewEntity()+" : "+masterTransferBean.getOldRollNumber()+" "+masterTransferBean.getStudentId());
			int insertSRSH=sqlMapClient.update("masterTransfer.insertIntoSRSH", masterTransferBean);
			
			StudentTracking studentTracking=new StudentTracking(masterTransferBean.getNewEntity(),masterTransferBean.getRollNumber(),
					masterTransferBean.getProgramCourseKey(),masterTransferBean.getSemesterStartDate(),masterTransferBean.getSemesterEndDate(),
					masterTransferBean.getSessionStartDate(),masterTransferBean.getSessionEndDate(),CRConstant.REGISTRATION_STATUS,
					CRConstant.ACTIVE_STATUS,masterTransferBean.getUserId(),masterTransferBean.getActivityId(),masterTransferBean.getActivityId());
			
			int sequence1=new StudentTrackingFunction(sqlMapClient,transactionTemplate).getStdentTrackingIssue(studentTracking);
			
			studentTracking.setSequenceNumber(sequence1+1);
			//Insert a student in student tracking with semester status YTR and program status ACT
			sqlMapClient.update("studentTrackingAndLogs.insertStudentTracking", studentTracking);
			
			List<CourseList> list=masterTransferBean.getCourseList();
			
			for(CourseList courseList:list){
				//insert student in student courses
				int insertSC=sqlMapClient.update("masterTransfer.insertIntoStudentCourse", courseList);
				System.out.println("Inserting course");
			}
						
			SystemValue systemValue=new SystemValue(masterTransferBean.getUniveristyId(),CRConstant.SWITCH_NUMBER_CODE);
			
			int sequenceNumber=0;
			if(oldSemesterDetails.getModeOfEntry().equalsIgnoreCase(CRConstant.REGULAR_ADMISSION_MODE)&&oldSemesterDetails.getSwitchNumber()==0){
					
				int switchNumber=new RegistrationFunction(sqlMapClient,transactionTemplate).getIncrementedId(systemValue)+1;
				
				sequenceNumber=oldSemesterDetails.getSequenceNumber()+1;
				
				systemValue.setValue(String.valueOf(switchNumber));
				systemValue.setModifierId(masterTransferBean.getUserId());
				masterTransferBean.setSwitchNumber(switchNumber);
				masterTransferBean.setSequenceNumber(sequenceNumber);
							
				int updateSystemValue=sqlMapClient.update("systemValue.updateSystemValue", systemValue);
				System.out.println("Value Updated");
					
			}
			else{
				masterTransferBean.setSwitchNumber(oldSemesterDetails.getSwitchNumber());
				masterTransferBean.setSequenceNumber(oldSemesterDetails.getSequenceNumber());
				sequenceNumber=oldSemesterDetails.getSequenceNumber();
			}
			
			//masterTransferBean.setOldRollNumber(oldSemesterDetails.getOldRollNumber());
			
			if(masterTransferBean.getOldProgram().equalsIgnoreCase(masterTransferBean.getNewProgram())){
				System.out.println("Same Program Id"+oldSemesterDetails.getProgramStatus()+"masterTransferBean.getOldProgram()="+masterTransferBean.getOldProgram());
			if(oldSemesterDetails.getProgramStatus().equalsIgnoreCase(CRConstant.ACTIVE_STATUS)||
					oldSemesterDetails.getProgramStatus().equalsIgnoreCase(CRConstant.STATUS_PASS)){
				System.out.println("Same either "+oldSemesterDetails.getProgramStatus());		
		
				if(oldSemesterDetails.getProgramStatus().equalsIgnoreCase(CRConstant.ACTIVE_STATUS)){
					//update student's status by SWT and else 
					masterTransferBean.setProgramStatus(CRConstant.SWITCH_MODE);
					RegistrationFunction registrationFunction=new RegistrationFunction(sqlMapClient,transactionTemplate);
					String programCourseKey=registrationFunction.getProgramCourseKey(new TransferNORInPSTBean(masterTransferBean.getOldProgram(),
							masterTransferBean.getOldBranch(),masterTransferBean.getOldSpecialization(),masterTransferBean.getOldSemester()));
					
					PreviousSemesterDetail previousSemesterData=new PreviousSemesterDetail(masterTransferBean.getRollNumber(),masterTransferBean.getNewEntity(),
							programCourseKey);
					List<PreviousSemesterDetail> previousSemesterResult=registrationFunction.getPreviousSessionDate(previousSemesterData);
					
					String semesterStartDate="";
					String semesterEndDate="";
					String preStatus="";
					for(PreviousSemesterDetail previous:previousSemesterResult){
						//System.out.println("coming inside ths ");
						semesterStartDate=previous.getPreviousSemesterStartDate();
						semesterEndDate=previous.getPreviousSemesterEndDate();
						System.out.println(semesterStartDate+" abc "+semesterEndDate);
					}//
					
					StudentTracking studentTrackingForProgram=new StudentTracking(masterTransferBean.getNewEntity(),masterTransferBean.getRollNumber(),
							programCourseKey,semesterStartDate,semesterEndDate,
							masterTransferBean.getSessionStartDate(),masterTransferBean.getSessionEndDate(),preStatus,
							CRConstant.SWITCH_MODE,masterTransferBean.getUserId(),masterTransferBean.getActivityId(),masterTransferBean.getActivityId());
					int sequence=new StudentTrackingFunction(sqlMapClient,transactionTemplate).getStdentTrackingIssue(studentTracking);
					
					studentTrackingForProgram.setSequenceNumber(sequence+1);
					//Insert a student in student tracking with semester status YTR and program status ACT
					sqlMapClient.update("studentTrackingAndLogs.insertStudentTracking", studentTrackingForProgram);
					System.out.println("Updated to switch");
					
				}
				if(oldSemesterDetails.getProgramStatus().equalsIgnoreCase(CRConstant.STATUS_PASS)){
					masterTransferBean.setProgramStatus(CRConstant.STATUS_PASS);
					System.out.println("Updated to PAS");
					
				}
				System.out.println(""+masterTransferBean.getSwitchNumber()+" : "+masterTransferBean.getSequenceNumber());
				sqlMapClient.update("masterTransfer.updateSPForSameProgram", masterTransferBean);
				System.out.println("Updated same progam");
			}//If Active_status and Status_Pass condition ends
			}//If Old Program and New program is same
			else{
				if(oldSemesterDetails.getProgramStatus().equalsIgnoreCase(CRConstant.ACTIVE_STATUS)||
						oldSemesterDetails.getProgramStatus().equalsIgnoreCase(CRConstant.STATUS_PASS)){
					
				//	int updateSP=sqlMapClient.update("masterTransfer.updateSPForDiffProgram", masterTransferBean);
					System.out.println("Updated Different Program");
					masterTransferBean.setProgramStatus(oldSemesterDetails.getProgramStatus());
				}//If Active_status and Status_Pass condition ends
				sqlMapClient.update("masterTransfer.updateSPForDiffProgram", masterTransferBean);
			}
			
			
			masterTransferBean.setProgramStatus(CRConstant.ACTIVE_STATUS);
			masterTransferBean.setModeOfEntry(CRConstant.SWITCH_ADMISSION_MODE);
			
			masterTransferBean.setSequenceNumber(sequenceNumber+1);
			int insertSP=sqlMapClient.update("masterTransfer.insertStudentProgram", masterTransferBean);
			
			//Students record is inserted into STUDENT PROGRAM
			System.out.println("Semester start date"+masterTransferBean.getSemesterStartDate());
			StudentTracking studentTracking1=new StudentTracking(masterTransferBean.getNewEntity(),masterTransferBean.getRollNumber(),
					masterTransferBean.getProgramCourseKey(),masterTransferBean.getSemesterStartDate(),masterTransferBean.getSemesterEndDate(),
					masterTransferBean.getSessionStartDate(),masterTransferBean.getSessionEndDate(),CRConstant.ACTIVE_STATUS,
					CRConstant.ACTIVITY_MASTER,masterTransferBean.getUserId(),masterTransferBean.getActivityId(),masterTransferBean.getActivityId());
			int sequence=new StudentTrackingFunction(sqlMapClient,transactionTemplate).getStdentTrackingIssue(studentTracking1);
			
			studentTracking1.setSequenceNumber(sequence+1);
			
			System.out.println("Inserting student program"+masterTransferBean.getEnrollmentNumber()+" and "+masterTransferBean.getOldRollNumber()+": "+
					masterTransferBean.getOldBranch()+" : "+masterTransferBean.getOldProgram());
			
			if(!masterTransferBean.getOldRollNumber().equalsIgnoreCase(masterTransferBean.getRollNumber())){
				
				PersonalDetailsBean personalDetailsBean=new PersonalDetailsBean(masterTransferBean.getUniveristyId(),
						masterTransferBean.getEnrollmentNumber(),masterTransferBean.getUserId());
				
				
				//object with personal details of a student
				PersonalDetailsBean personalDetails=getPersonDetails(personalDetailsBean);
				
				EmailTableBean emailTable=new EmailTableBean(masterTransferBean.getStudentId(),masterTransferBean.getNewEntity(),masterTransferBean.getNewProgram(),
						masterTransferBean.getNewBranch(), masterTransferBean.getNewSpecialization(), masterTransferBean.getNewSemester(),
							CRConstant.USER_STUDENT_GROUP_ID, masterTransferBean.getRollNumber(), personalDetails.getPrimaryEmailId(),
							"UI", true) ;
				sqlMapClient.insert("emailTable.insertIntoEMailTable", emailTable);
			}
			
			sqlMapClient.update("masterTransfer.updateTempStudentProgram", masterTransferBean);
			sqlMapClient.update("masterTransfer.updateTempStudentCourse", masterTransferBean);
			
			
			
			System.out.println("Transaction ends");
			}catch(DataAccessException e){
				System.out.println("Exception inside SWT "+e.getMessage());
				errorLogs.setReasonCode("DBI");
				errorLogs.setDescription("Database inconsistancy");
				errorLogs.setProcessFlag(CRConstant.ERROR_STATUS);
				try{
				sqlMapClient.insert("studentTrackingAndLogs.insertStudentErrorLog", errorLogs);
				}catch(Exception error){
					System.out.println(error.getMessage());
				}
					} catch (Exception e) {
				// TODO Auto-generated catch block
						System.out.println("Exception inside SWT catch: "+e.getMessage());
						errorLogs.setReasonCode("DBI");
						errorLogs.setDescription("Database inconsistancy");
						errorLogs.setProcessFlag(CRConstant.ERROR_STATUS);
						try{
						sqlMapClient.insert("studentTrackingAndLogs.insertStudentErrorLog", errorLogs);
						}catch(Exception error){
							System.out.println(error.getMessage());
						}
				}
			}//
	
        });
	
	}

	public void transferNEWStudentIntoMaster(final MasterTransferBean masterTransferBean,
			final PersonalDetailsBean personalDetailsBean,final ErrorLogs errorLogs){
		
		transactionTemplate.execute(new TransactionCallbackWithoutResult(){
			//Object save=null;
		
			@Override
			public void doInTransactionWithoutResult(TransactionStatus status) {
			try{
				//save=status.createSavepoint();
				System.out.println("Master Transfer NEW"+masterTransferBean.getStudentId());
			SystemValue systemValue=new SystemValue(masterTransferBean.getUniveristyId(),CRConstant.STUDENT_ID_CODE);
			
			List<PersonalDetailsBean> personExist=new ArrayList<PersonalDetailsBean>();
			
			personExist=sqlMapClient.queryForList("masterTransfer.enrollmentExist", personalDetailsBean);
			
			PersonalDetailsBean person=personalDetailsBean;
			
			if(personExist.size()==0){
				int studentId=new RegistrationFunction(sqlMapClient,transactionTemplate).getIncrementedId(systemValue)+1;
				
				String generateSystemId="S" + masterTransferBean.getNewEntity()+String.valueOf(new java.util.Date().getYear()/10)+String.format("%07d",studentId);
				
				systemValue.setModifierId(masterTransferBean.getUserId());
				systemValue.setValue(String.format("%07d",studentId));
				
				int updateSystemValue=sqlMapClient.update("systemValue.updateSystemValue", systemValue);
				
				//Insert stduent into address_master and student_master
				
				person.setStudentId(generateSystemId);
				
				masterTransferBean.setStudentId(generateSystemId);
				
				int insertPersonDetails=sqlMapClient.update("masterTransfer.insertStudentPersonalDetails", person);
				
				
				
				System.out.println("Coming inside phone:"+personalDetailsBean.getHomePhone());
				
				int insertPermanentAddressDetails=sqlMapClient.update("masterTransfer.insertStudentAddressDetails", new AddressDetailBean(CRConstant.PERMANENT_ADDRESS,CRConstant.USER_STUDENT_GROUP_ID,
						personalDetailsBean.getPermanentAddress(), personalDetailsBean.getPermanentCity(), 
						personalDetailsBean.getPermanentState(),personalDetailsBean.getPermanentPinCode(),
						personalDetailsBean.getHomePhone(),personalDetailsBean.getExtraPhone(), personalDetailsBean.getOtherPhone(), 
						personalDetailsBean.getFax(), generateSystemId,personalDetailsBean.getUserId()));
							
				if(personalDetailsBean.getCorrespondentAddress()!=null){
				int insertCorresPondentDetails=sqlMapClient.update("masterTransfer.insertStudentAddressDetails", new AddressDetailBean(CRConstant.CORRESPONDENT_ADDRESS,CRConstant.USER_STUDENT_GROUP_ID,
						personalDetailsBean.getCorrespondentAddress(), personalDetailsBean.getCorrespondentCity(), 
						personalDetailsBean.getCorrespondentState(),personalDetailsBean.getCorrespondentPinCode(),
						personalDetailsBean.getHomePhone(),personalDetailsBean.getExtraPhone(), personalDetailsBean.getOtherPhone(), 
						personalDetailsBean.getFax(), generateSystemId,personalDetailsBean.getUserId()));
				}
			
			}
			
			
			int insertSP=sqlMapClient.update("masterTransfer.insertNewStudentProgram", masterTransferBean);
			StudentTracking studentTrackingForProgram=new StudentTracking(masterTransferBean.getNewEntity(),masterTransferBean.getRollNumber(),
					masterTransferBean.getProgramCourseKey(),masterTransferBean.getSemesterStartDate(),masterTransferBean.getSemesterEndDate(),
					masterTransferBean.getSessionStartDate(),masterTransferBean.getSessionEndDate(),CRConstant.REGISTRATION_STATUS,
					CRConstant.ACTIVE_STATUS,masterTransferBean.getUserId(),masterTransferBean.getActivityId(),masterTransferBean.getActivityId());
			int sequenceForProgram=new StudentTrackingFunction(sqlMapClient,transactionTemplate).getStdentTrackingIssue(studentTrackingForProgram);
			
			studentTrackingForProgram.setSequenceNumber(sequenceForProgram+1);
			//Insert a student in student tracking with semester status YTR and program status ACT
			sqlMapClient.update("studentTrackingAndLogs.insertStudentTracking", studentTrackingForProgram);
			
			
			int insertSRSH=sqlMapClient.update("masterTransfer.insertIntoSRSH", masterTransferBean);
			StudentTracking studentTracking=new StudentTracking(masterTransferBean.getNewEntity(),masterTransferBean.getRollNumber(),
					masterTransferBean.getProgramCourseKey(),masterTransferBean.getSemesterStartDate(),masterTransferBean.getSemesterEndDate(),
					masterTransferBean.getSessionStartDate(),masterTransferBean.getSessionEndDate(),CRConstant.REGISTRATION_STATUS,
					CRConstant.ACTIVE_STATUS,masterTransferBean.getUserId(),masterTransferBean.getActivityId(),masterTransferBean.getActivityId());
			int sequence=new StudentTrackingFunction(sqlMapClient,transactionTemplate).getStdentTrackingIssue(studentTracking);
			
			studentTracking.setSequenceNumber(sequence+1);
			//Insert a student in student tracking with semester status YTR and program status ACT
			sqlMapClient.update("studentTrackingAndLogs.insertStudentTracking", studentTracking);
			
			List<CourseList> list=masterTransferBean.getCourseList();
			
			for(CourseList courseList:list){
				//insert student in student courses
				int insertSC=sqlMapClient.update("masterTransfer.insertIntoStudentCourse", courseList);
				
			}			
			
			EmailTableBean emailTable=new EmailTableBean(masterTransferBean.getStudentId(),masterTransferBean.getNewEntity(),masterTransferBean.getNewProgram(),
					masterTransferBean.getNewBranch(), masterTransferBean.getNewSpecialization(), masterTransferBean.getNewSemester(),
						CRConstant.USER_STUDENT_GROUP_ID, masterTransferBean.getRollNumber(), personalDetailsBean.getPrimaryEmailId(),
						"UI", true) ;
			sqlMapClient.insert("emailTable.insertIntoEMailTable", emailTable);
			
			int updateTSP=sqlMapClient.update("masterTransfer.updateTempStudentProgram", masterTransferBean);
			int updateTSC=sqlMapClient.update("masterTransfer.updateTempStudentCourse", masterTransferBean);
			
			
			
			System.out.println("Transaction is complete in NEW");
			}catch(DataAccessException e){
				System.out.println("before save anil inside data access="+status.isNewTransaction());
				errorLogs.setReasonCode("DBI");
				errorLogs.setDescription("Database inconsistancy");
				errorLogs.setProcessFlag(CRConstant.ERROR_STATUS);
				try{
				sqlMapClient.insert("studentTrackingAndLogs.insertStudentErrorLog", errorLogs);
				}catch(Exception error){
					System.out.println(error.getMessage());
				}
					} catch (Exception e) {
				// TODO Auto-generated catch block
				System.out.println("Coming inside exception NEW"+e.getMessage());
				errorLogs.setReasonCode("DBI");
				errorLogs.setDescription("Database inconsistancy");
				errorLogs.setProcessFlag(CRConstant.ERROR_STATUS);
				try{
				sqlMapClient.insert("studentTrackingAndLogs.insertStudentErrorLog", errorLogs);
				}catch(Exception error){
					System.out.println(error.getMessage());
				}
				
			}
			}//
		});
			
	}

	public OldSemesterDetails getOldProgramDetails(MasterTransferBean masterTransferBean) {
		// TODO Auto-generated method stub
		OldSemesterDetails oldSemesterDetails=null;
		try{
			List<MasterTransferBean> oldDetails=(List<MasterTransferBean>)sqlMapClient.queryForList("masterTransfer.getOldProgramDetail",masterTransferBean);
			for(MasterTransferBean oldSemesterDetail:oldDetails){
				System.out.println(oldSemesterDetail.getModeOfEntry()+oldSemesterDetail.getStatus()+oldSemesterDetail.getSwitchNumber()+
						oldSemesterDetail.getSequenceNumber()+masterTransferBean.getEnrollmentNumber()+oldSemesterDetail.getOldRollNumber());
				oldSemesterDetails=new OldSemesterDetails(oldSemesterDetail.getModeOfEntry(),oldSemesterDetail.getStatus(),
						oldSemesterDetail.getSwitchNumber(),oldSemesterDetail.getSequenceNumber(),masterTransferBean.getEnrollmentNumber(),oldSemesterDetail.getOldRollNumber());
			}
						
		}catch(Exception e){
			System.out.println("Exception inside getting oldsemester details: "+e.getMessage());
		}
		return oldSemesterDetails;
	}

	

	public ErrorReason validateDataForNORStudent(
			MasterTransferBean masterTransferBean,
			List<CourseList> courseList) {
		// TODO Auto-generated method stub
		boolean b=true;
		String reasonCode="";
		String description="";
		try{
			if(masterTransferBean.getEnrollmentNumber()==null||masterTransferBean.getEnrollmentNumber().equalsIgnoreCase(null)
					||masterTransferBean.getOldEntity()==null || masterTransferBean.getOldEntity().equalsIgnoreCase(null)||
					masterTransferBean.getOldProgram()==null|| masterTransferBean.getOldProgram().equalsIgnoreCase(null)||
					masterTransferBean.getOldBranch()==null|| masterTransferBean.getOldBranch().equalsIgnoreCase(null)||
					masterTransferBean.getOldSpecialization()==null|| masterTransferBean.getOldSpecialization().equalsIgnoreCase(null)||
					masterTransferBean.getOldSemester()==null|| masterTransferBean.getOldSemester().equalsIgnoreCase(null)||
					masterTransferBean.getRollNumber()==null|| masterTransferBean.getRollNumber().equalsIgnoreCase(null)||
					masterTransferBean.getStatusInSemester()==null|| masterTransferBean.getStatusInSemester().equalsIgnoreCase(null)
					){
				b=false;
				reasonCode="NNA";
				description="Some required information is missing";
			}
			
			if(courseList.size()==0){
				b=false;
				reasonCode="NCF";
				description="No course found";
			}
			
			
		}catch(Exception e){
			System.out.println("Some Exception is there");
			b=false;
			reasonCode="NNA";
			description="Some required information is missing";
			System.out.println("Exception inside validating NOR"+e.getMessage());
		}
		return new ErrorReason(reasonCode,description,b);
	}
	
	public ErrorReason validateDataForSWTStudent(
			MasterTransferBean masterTransferBean,
			List<CourseList> courseList,OldSemesterDetails oldSemesterDetails) {
		// TODO Auto-generated method stub
		boolean b=true;
		String reasonCode="";
		String description="";
		try{
			if(masterTransferBean.getOldProgram().equalsIgnoreCase(masterTransferBean.getNewProgram()) && masterTransferBean.getOldProgram()!=null){
					
				if(masterTransferBean.getEnrollmentNumber()==null
							||masterTransferBean.getOldEntity()==null
							||masterTransferBean.getOldProgram()==null
							||masterTransferBean.getOldBranch()==null|| 
							masterTransferBean.getOldSpecialization()==null||
							masterTransferBean.getOldSemester()==null||
							masterTransferBean.getRollNumber()==null||
							oldSemesterDetails.getOldRollNumber()==null
							){
									b=false;
									reasonCode="NNA";
									description="Some required information is missing";
						}
					else{
						if(masterTransferBean.getEnrollmentNumber()==null||masterTransferBean.getEnrollmentNumber().equalsIgnoreCase(null)){
									b=false;
									reasonCode="NNA";
									description="Enrollment number is missing";
						}
					}
			}
			
			if(courseList.size()==0){
				b=false;
				reasonCode="NCF";
				description="No course found";
			}
			
			
		}catch(Exception e){
			b=false;
			reasonCode="NNA";
			description="Some required information is missing";
			
		}
		return new ErrorReason(reasonCode,description,b);
	}

	public ErrorReason validateDataForNEWStudent(
			MasterTransferBean masterTransferBean,
			List<CourseList> courseList,PersonalDetailsBean personalDetailsBean) {
		// TODO Auto-generated method stub
		boolean b=true;
		String reasonCode="";
		String description="";
		try{
			List<PersonalDetailsBean> personExist=new ArrayList<PersonalDetailsBean>();
			
			personExist=sqlMapClient.queryForList("masterTransfer.enrollmentExist", personalDetailsBean);
			if(personExist.size()==0){
			if(masterTransferBean.getEnrollmentNumber()==null||masterTransferBean.getEnrollmentNumber().equalsIgnoreCase(null)||
					masterTransferBean.getRollNumber()==null|| masterTransferBean.getRollNumber().equalsIgnoreCase(null)||
					personalDetailsBean.getStudentFirstName()==null||personalDetailsBean.getStudentFirstName().equalsIgnoreCase(null)||
					personalDetailsBean.getFatherFirstName()==null||personalDetailsBean.getFatherFirstName().equalsIgnoreCase(null)||
					personalDetailsBean.getDateOfBirth()==null||personalDetailsBean.getDateOfBirth().equalsIgnoreCase(null)||
					personalDetailsBean.getCategoryCode()==null||personalDetailsBean.getCategoryCode().equalsIgnoreCase(null)||
					personalDetailsBean.getGender()==null|| personalDetailsBean.getGender().equalsIgnoreCase(null)
					){
				b=false;
				reasonCode="NNA";
				description="Some required information is missing";
			}
			}
			
			
			if(courseList.size()==0){
				b=false;
				reasonCode="NCF";
				description="No course found";
			}
			
			
		}catch(Exception e){
			b=false;
			reasonCode="NNA";
			description="Some required information is missing";
			System.out.println("Exception inside validating NEW "+e.getMessage());
		}
		return new ErrorReason(reasonCode,description,b);
	}
	
	public PersonalDetailsBean getPersonDetails(PersonalDetailsBean personalDetailsBean){
		 PersonalDetailsBean personalDetail=new PersonalDetailsBean();
		 List<AddressDetailBean> addressDetail=new ArrayList<AddressDetailBean>();
		try{
			List<PersonalDetailsBean> personalDetails=(List<PersonalDetailsBean>)sqlMapClient.queryForList("masterTransfer.getPersonalDetails", personalDetailsBean);
				
			for(PersonalDetailsBean personDetails: personalDetails){
				personalDetail=personDetails;
				
			}
		
		}catch(Exception e){
			System.out.println("Exception in getting personal details "+e.getMessage());
		}
		
		return personalDetail;
	}
	
	public List<CourseList> getCourseList(MasterTransferBean masterTransferBean){
		List<CourseList> totalCourse=new ArrayList<CourseList>();
		System.out.println("Coming inside getCourseList"+masterTransferBean.getNewProgram()+
				masterTransferBean.getRegistrationNumber()+masterTransferBean.getEnrollmentNumber()+
				masterTransferBean.getRollNumber()+masterTransferBean.getNewBranch()
				+masterTransferBean.getNewSpecialization()+masterTransferBean.getSemesterStartDate()+
				masterTransferBean.getSemesterEndDate()+masterTransferBean.getNewSemester());
		try{
			
		List<MasterTransferBean> courses=(List<MasterTransferBean>)sqlMapClient.queryForList("masterTransfer.getListOfCourse", masterTransferBean);
			System.out.println("course:"+courses.size());	
		for(MasterTransferBean course:courses){
				totalCourse.add(new CourseList(masterTransferBean.getRollNumber(),masterTransferBean.getProgramCourseKey(),
						masterTransferBean.getSemesterStartDate(),masterTransferBean.getSemesterEndDate(),
						course.getCourseCode(),course.getCourseStatus(),masterTransferBean.getUserId()));
				
				System.out.println("inside courses: "+masterTransferBean.getRollNumber()+masterTransferBean.getProgramCourseKey()+
						masterTransferBean.getSemesterStartDate()+masterTransferBean.getSemesterEndDate()+
						course.getCourseCode()+course.getCourseStatus()+masterTransferBean.getUserId());
				
			}
		}catch(Exception e){
			System.out.println("Exception in course list"+e);
		}
		return totalCourse;
	}
	
	public List<CourseList> getCourseListForOldStudent(MasterTransferBean masterTransferBean){
		List<CourseList> totalCourse=new ArrayList<CourseList>();

		try{
			
		List<MasterTransferBean> courses=(List<MasterTransferBean>)sqlMapClient.queryForList("masterTransfer.getListOfCourseForOldStudent", masterTransferBean);
			System.out.println("course:"+courses.size());	
		for(MasterTransferBean course:courses){
				totalCourse.add(new CourseList(masterTransferBean.getRollNumber(),masterTransferBean.getProgramCourseKey(),
						masterTransferBean.getSemesterStartDate(),masterTransferBean.getSemesterEndDate(),
						course.getCourseCode(),course.getCourseStatus(),masterTransferBean.getUserId()));
				
				System.out.println("Getting List of courses: "+masterTransferBean.getRollNumber()+masterTransferBean.getProgramCourseKey()+
						masterTransferBean.getSemesterStartDate()+masterTransferBean.getSemesterEndDate()+
						course.getCourseCode()+course.getCourseStatus()+masterTransferBean.getUserId());
				
			}
		}catch(Exception e){
			System.out.println("Exception in get list for course for old student"+e);
		}
		return totalCourse;
	}

}
